package com.xujiang.common.ui;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.method.ScrollingMovementMethod;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.xujiang.common.R;
import com.xujiang.common.R2;
import com.xujiang.common.util.L;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 调用android 底层命令行工具
 *
 * @author xujiang
 * @version 2017-05-10 09:50
 */
public class CMD extends BaseActivity {
    private static final String TAG = CMD.class.getSimpleName();

    @BindView(R2.id.bt_send)
    Button btSend;
    @BindView(R2.id.tv_show)
    TextView tvShow;
    @BindView(R2.id.et_input)
    EditText etInput;

    private int offset;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.layout_cmd);
        ButterKnife.bind(this);
        tvShow.setMovementMethod(ScrollingMovementMethod.getInstance());
    }

    @OnClick(R2.id.bt_send)
    public void onViewClicked() {
        String cmd = etInput.getText().toString().trim();
        do_exec(cmd);
    }

    public void do_exec(String cmd){
        String s = "/n";
        try{
            Process p = Runtime.getRuntime().exec(cmd);
            BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream()));
            String line = null;
            while ((line = in.readLine()) != null){
                s += line+"/n";
            }
        }catch (IOException e){
            L.e(TAG,e);
        }
        tvShow.append(s);
        offset=tvShow.getLineCount()*tvShow.getLineHeight();
        if(offset>tvShow.getHeight()){
            tvShow.scrollTo(0,offset-tvShow.getHeight());
        }

    }

}
